//
//  CountryBarPlot.m
//  Balance
//
//  Created by Calvin Kuo on 12-04-23.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
/*
 Status: changed
 Last Merge Date: 05-30-2012
 Last Change Date: 
 Changes:
 1. graph title
 2. bar color
 
 */


#import "CountryBarPlot.h"
#import "Balance.h"

#define kDefaultPlot @"default"

@implementation CountryBarPlot

@synthesize countryBalances = _countryBalances;
@synthesize countryNames = _countryNames;



- (id) init {
    self = [super init];
    if(self){
        self.countryNames = nil;
        self.countryBalances = nil;

    }
    return self;
}


- (id)initWithCountryNames:(NSArray *)selectedCountryNames andCountryBalances:(NSArray *)selectedCountryBalances
{
    self = [self init];
    if (self) 
    {
        self.countryNames = selectedCountryNames;
        self.countryBalances = selectedCountryBalances;
        /*for (NSString *code in self.countryNames){
         NSLog(@"self.countryNames=%@",code);
         }
         for (Balance *bmm in _countryBalances){
         NSLog(@"_countryBalances=%@",bmm.balanceAmount);
         };*/
    }
    return self;
}

- (void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme
{
    
    CGRect bounds = layerHostingView.bounds;
    
    // create and assign chart to the hosting view.
    graph = [[CPTXYGraph alloc] initWithFrame:bounds];
    layerHostingView.hostedGraph = graph;
    layerHostingView.backgroundColor = [UIColor colorWithWhite:0.7f alpha:1.0f]; 
    
    CPTGradient *plotAreaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor colorWithGenericGray:0.9f]endingColor:[CPTColor colorWithGenericGray:0.6f]];
    plotAreaGradient.angle = -90.0;
    graph.plotAreaFrame.plotArea.fill = [CPTFill fillWithGradient:plotAreaGradient]; 

    [graph applyTheme:theme];
    
    graph.plotAreaFrame.masksToBorder = NO;
    
    graph.paddingLeft = 100.0;
	graph.paddingTop = 120.0;  //50.0
	graph.paddingRight = 90.0;
	graph.paddingBottom = 120.0;
    
    CPTMutableTextStyle *blackTextStyle = [[CPTMutableTextStyle alloc] init];
	//blackTextStyle.color = [CPTColor blackColor];
    blackTextStyle.color = [CPTColor colorWithComponentRed:0.2 green:0.2 blue:0.2 alpha:0.82]; //RGB:R51-G51-B51
	blackTextStyle.fontSize = 20.0;
    graph.titleTextStyle = blackTextStyle;
    graph.titleDisplacement = CGPointMake(0.0, 90.0); 
    graph.title = @"Receivables Aging Balance By Country";
    
    
    // chang the chart layer orders so the axis line is on top of the bar in the chart.
    NSArray *chartLayers = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:CPTGraphLayerTypeAxisLines],  
                            [NSNumber numberWithInt:CPTGraphLayerTypePlots], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeMajorGridLines], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeMinorGridLines],
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisLabels], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisTitles], nil];
    
    graph.topDownLayerOrder = chartLayers;
    
	// Add plot space for horizontal bar charts
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(50000)];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(6)];
    
    // Setting X-Axis
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x = axisSet.xAxis;
    x.labelingPolicy = CPTAxisLabelingPolicyNone;
    x.title = @"Country";
    
    x.titleOffset = 30.0f;
    x.majorTickLineStyle = nil;
    x.minorTickLineStyle = nil;
    x.majorIntervalLength = CPTDecimalFromString(@"1");
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    x.labelExclusionRanges = [NSArray arrayWithObjects:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(6) length:CPTDecimalFromInt(1)], nil];
    
    // Use custom x-axis label so it will display product A, B, C... instead of 1, 2, 3, 4
    NSMutableArray *labels = [[NSMutableArray alloc] initWithCapacity:[_countryNames count]];
    int idx = 0;
    for (NSString *product in _countryNames)
    {
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:product textStyle:x.labelTextStyle];
        label.tickLocation = CPTDecimalFromInt(idx);
        label.offset = 5.0f;
        [labels addObject:label];
        idx++;
    }
    x.axisLabels = [NSSet setWithArray:labels];
    
    // Setting up y-axis
	CPTXYAxis *y = axisSet.yAxis;
    y.majorIntervalLength = CPTDecimalFromInt(10000);
    y.minorTicksPerInterval = 0;
    y.minorGridLineStyle = nil;
    y.title = @"Amount Overdue";
    y.labelExclusionRanges = [NSArray arrayWithObjects:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(0)], nil];
    
    CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
	borderLineStyle.lineWidth = 2.f;
    borderLineStyle.lineColor = [CPTColor colorWithComponentRed:0.22f green:0.55f blue:0.71f alpha:1.0f];
      
    //************************************************************************
    lowBarPlot = [[CPTBarPlot alloc] init];
    CPTColor *aboveAreaColor = [CPTColor colorWithComponentRed:0.882 green:0.251 blue:0.141 alpha:1.0];   //RGB: 225-64-36  (orange)
    CPTColor *aboveAreaEndColor = [CPTColor colorWithComponentRed:0.922 green:0.361 blue:0.125 alpha:1.0]; //RGB: 235-92-32  (orange)
    CPTGradient *aboveAreaGradient = [CPTGradient gradientWithBeginningColor:aboveAreaColor endingColor:aboveAreaEndColor];
    aboveAreaGradient.angle = -90.0;
    CPTFill *aboveAreaGradientFill = [CPTFill fillWithGradient:aboveAreaGradient];
    lowBarPlot.fill = aboveAreaGradientFill;
    //lowBarPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:0.20 blue:0.0 alpha:1.0]];
    lowBarPlot.lineStyle = borderLineStyle;
    lowBarPlot.barWidth = CPTDecimalFromString(@"0.6");
    lowBarPlot.barBasesVary = YES;
    lowBarPlot.dataSource = self;
    lowBarPlot.barCornerRadius = 2.0f;
    lowBarPlot.identifier = kDefaultPlot;
    lowBarPlot.delegate = self;
    
    //************************************************************************
    midBarPlot = [[CPTBarPlot alloc] init];
    CPTColor *belowAreaColor = [CPTColor colorWithComponentRed:0.051 green:0.388 blue:0.894 alpha:1.0];
    //RGB: 130-99-228  (blue)
    CPTColor *belowAreaEndColor = [CPTColor colorWithComponentRed:0.129 green:0.545 blue:0.894 alpha:1.0];//RGB: 33-139-228  (blue)
    CPTGradient *belowAreaGradient = [CPTGradient gradientWithBeginningColor:belowAreaColor endingColor:belowAreaEndColor];
    belowAreaGradient.angle = -90.0;
    CPTFill *belowAreaGradientFill = [CPTFill fillWithGradient:belowAreaGradient];
    midBarPlot.fill = belowAreaGradientFill;
    //midBarPlot.fill = [CPTFill fillWithColor:[CPTColor greenColor]];
    //midBarPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:0.0 green:1.0 blue:0.0 alpha:1.0]];
    midBarPlot.lineStyle = borderLineStyle;
    midBarPlot.barWidth = CPTDecimalFromString(@"0.6");
    midBarPlot.barBasesVary = YES;
    midBarPlot.dataSource = self;
    midBarPlot.barCornerRadius = 2.0f;
    midBarPlot.identifier = kDefaultPlot;
    midBarPlot.delegate = self;
    
    //************************************************************************
    highBarPlot = [[CPTBarPlot alloc] init];
    CPTColor *balanceAreaColor  = [CPTColor colorWithComponentRed:0.078 green:0.529 blue:0.0 alpha:1.0]; //RGB: 20-135-0  (green)
    CPTColor *balanceAreaEndColor  = [CPTColor colorWithComponentRed:0.216 green:0.671 blue:0.004 alpha:1.0]; //RGB: 55-171-1  (green)
    CPTGradient *balanceAreaGradient = [CPTGradient gradientWithBeginningColor:balanceAreaColor endingColor:balanceAreaEndColor];
    balanceAreaGradient.angle = -90.0;
    CPTFill *balanceAreaGradientFill = [CPTFill fillWithGradient:balanceAreaGradient];
    highBarPlot.fill = balanceAreaGradientFill;
    //highBarPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:0.0 green:0.3 blue:1.0 alpha:0.9]];
    highBarPlot.lineStyle = borderLineStyle;
    highBarPlot.barWidth = CPTDecimalFromString(@"0.6");
    highBarPlot.barBasesVary = YES;
    highBarPlot.dataSource = self;
    highBarPlot.barCornerRadius = 2.0f;
    highBarPlot.identifier = kDefaultPlot;
    highBarPlot.delegate = self;
    
    //legend for the plots
    highBarPlot.title = @"Receivables Aging Balance";
    midBarPlot.title = @"1-90 Day Delinquent";
    lowBarPlot.title = @"90+ Day Delinquent";
    CPTLegend *lineLegend = [CPTLegend legendWithPlots:[NSArray arrayWithObjects:highBarPlot, midBarPlot, lowBarPlot, nil]]; 
    lineLegend.numberOfColumns = 3;
    graph.legend= lineLegend;
    graph.legend.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
    graph.legend.cornerRadius = 5.0;
    graph.legend.swatchSize = CGSizeMake(10.0, 30.0);
    //graph.legend.swatchCornerRadius = 5.0f;
    graph.legend.swatchSize = CGSizeZero;
    graph.legendAnchor = CPTRectAnchorTop;  //CPTRectAnchorRight
    graph.legendDisplacement = CGPointMake(10.0, -80.0);  //position of the legend
    
    CPTMutableTextStyle *legendTextStyle = [[CPTMutableTextStyle alloc] init];
	legendTextStyle.color = [CPTColor darkGrayColor];
	legendTextStyle.fontSize = 11.0;
    legendTextStyle.fontName = @"Helvetica-Bold";
    graph.legend.textStyle = legendTextStyle;
    
    
    
    //Add animation
 /*   
    //CABasicAnimation *scaling =[CABasicAnimation animationWithKeyPath:@"transform.scale"]; 
    CABasicAnimation *scaling =[CABasicAnimation animationWithKeyPath:@"transform.scale.y"]; 
    scaling.fromValue = [NSNumber numberWithFloat:0.0];
    scaling.toValue = [NSNumber numberWithFloat:1.0];
    scaling.duration = 5.0f; // Duration
    scaling.removedOnCompletion = NO;
    scaling.fillMode = kCAFillModeForwards;
    
    //lowBarPlot.anchorPoint = CGPointMake(0.0, 0.0); 
    lowBarPlot.anchorPoint = CGPointMake(0.0, 1.0); 
    //lowBarPlot.barOffsetScale = 0.0f; 
    [lowBarPlot addAnimation:scaling forKey:@"scaling"]; 
    [graph addPlot:lowBarPlot toPlotSpace:plotSpace];
    
    //midBarPlot.anchorPoint = CGPointMake(0.0, 0.5);
    midBarPlot.anchorPoint = CGPointMake(0.0, 1.0); 
    //midBarPlot.barOffsetScale = 0.0f; 
    [midBarPlot addAnimation:scaling forKey:@"scaling"]; 
    [graph addPlot:midBarPlot toPlotSpace:plotSpace];
    
    highBarPlot.anchorPoint = CGPointMake(0.0, 1.0); 
    //highBarPlot.barOffsetScale = 0.0f; 
    [highBarPlot addAnimation:scaling forKey:@"scaling"]; 
    [graph addPlot:highBarPlot toPlotSpace:plotSpace];
*/
    [graph addPlot:lowBarPlot toPlotSpace:plotSpace];
    [graph addPlot:midBarPlot toPlotSpace:plotSpace];
    [graph addPlot:highBarPlot toPlotSpace:plotSpace];
}



#pragma mark - CPTPlotDataSource Delegates
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    
    return [_countryNames count];
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    if (index == 0)
        return nil;
    
    NSNumber *num = nil;
    if (fieldEnum == CPTBarPlotFieldBarLocation)
    {
        num = [NSNumber numberWithInt:index];
    }
    else if (fieldEnum == CPTBarPlotFieldBarTip)
    {
        if (plot == lowBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            num = bal.aboveNinetyDaysAmount;
        } else if (plot == midBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            int n1 = [bal.aboveNinetyDaysAmount intValue] + [bal.belowNinetyDaysAmount intValue];
            num = [NSNumber numberWithInt:n1];                                                 
        } else if (plot == highBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            num = bal.balanceAmount;
        }
    }
    else if (fieldEnum == CPTBarPlotFieldBarBase){
        if (plot == lowBarPlot){
            num = [NSNumber numberWithInt:0];
        } else if (plot == midBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            num = bal.aboveNinetyDaysAmount;
        } else if (plot == highBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            int n2 = [bal.aboveNinetyDaysAmount intValue] + [bal.belowNinetyDaysAmount intValue];
            num = [NSNumber numberWithInt:n2];             
        }
                   
    }

        
  
    //NSLog(@"index =%d, country balance num=%@,fieldEnum=%d", index, num, fieldEnum);
    return num;

}    


@end
